package com.koron.car.web.motorcade.service.impl;

import com.koron.car.web.carledger.bean.query.CarQuery;
import com.koron.car.web.carledger.bean.vo.CarVO;
import com.koron.car.web.carledger.service.CarService;
import com.koron.car.web.motorcade.bean.Motorcade;
import com.koron.car.web.motorcade.mapper.MotorcadeMapper;
import com.koron.car.web.motorcade.service.MotorcadeService;
import com.koron.common.core.util.CodeTools;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.koron.ebs.mybatis.TaskAnnotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author twcao
 * @title: MotorcadeServiceImpl
 * @projectName GDH_EAM_V2
 * @description: 车队service实现
 * @date 2022/2/2617:10
 */
@Service
public class MotorcadeServiceImpl implements MotorcadeService {

    @Autowired
    private CarService carService;

    /**
     * 查询多条数据
     * @param factory
     * @param name 车队名字
     * @return 对象列表
     */
    @Override
    @TaskAnnotation("queryList")
    public List<Motorcade> queryList(SessionFactory factory, String name) {
        MotorcadeMapper mapper = factory.getMapper(MotorcadeMapper.class);
        Motorcade query = new Motorcade();
        query.setName(name);
        query.setDeleteFlag(false);
        return mapper.queryList(query);
    }

    /**
     * 新增数据
     * @param factory
     * @param motorcade 实例对象
     * @return 实例对象
     */
    @Override
    @TaskAnnotation("saveOrUpdate")
    public Motorcade saveOrUpdate(SessionFactory factory, Motorcade motorcade) {
        Assert.isTrue(motorcade != null && StringUtils.isNotBlank(motorcade.getName()), "车队名称不能为空");
        MotorcadeMapper mapper = factory.getMapper(MotorcadeMapper.class);
        if (StringUtils.isBlank(motorcade.getId())) {
            motorcade.setId(CodeTools.getCode32());
        }
        Motorcade db = mapper.queryByName(motorcade.getName());
        if (db != null) {
            Assert.isTrue(StringUtils.equalsIgnoreCase(db.getId(), motorcade.getId()), "车队名称已经存在");
        }
        motorcade.setDeleteFlag(false);
        mapper.saveOrUpdate(motorcade);
        return motorcade;
    }

    /**
     * 通过主键删除数据
     *
     * @param factory
     * @param id      主键
     * @return 是否成功
     */
    @Override
    @TaskAnnotation("hiddenById")
    public Boolean hiddenById(SessionFactory factory, String id) {
        MotorcadeMapper mapper = factory.getMapper(MotorcadeMapper.class);
        Motorcade motorcade = mapper.queryById(id);
        Assert.notNull(motorcade, "车队不存在");
        List<CarVO> carVOS = carService.queryList(factory, new CarQuery().setMotorcade(id));
        Assert.isTrue(CollectionUtils.isEmpty(carVOS),"该车队下存在车辆信息，无法删除");
        mapper.hiddenById(id);
        return true;
    }
}
